import React from 'react';
import DraggerUpload from './DraggerUpload';
import ImageViewer from '@/components/Viewers/ImageViewer';
import { getTypeIcon, getFileType } from '@/components/Viewers/FileViewer';

export default class FileUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      images: props.fileList
        ? props.fileList
            .filter(f => f.type && f.type.indexOf('image') >= 0)
            .map(f => ({
              uid: f.uid,
              alt: f.name,
              src: f.url,
            }))
        : [],
    };
  }

  handlePreview = file => {
    const type = getFileType(file);
    if (type === 'image') {
      // 显示图片预览框
      const { images } = this.state;
      let index = 0;
      images.forEach((f, i) => {
        if (f.uid === file.uid) index = i;
      });
      this.setState({
        visible: true,
        index,
      });
    } else if (type === 'pdf') {
      window.open(file.url);
    } else if (file.url) {
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = file.url;
      link.download = file.name;
      link.click();
    }
  };

  handleChange = ({ file, fileList }) => {
    const { onChange } = this.props;
    if (file.status === 'done' || file.status === 'removed') {
      const images = fileList
        .filter(f => f.status === 'done' && f.type.indexOf('image') >= 0)
        .map(f => ({
          uid: f.uid,
          alt: f.name,
          src: f.url || URL.createObjectURL(f.originFileObj),
        }));
      this.setState({ images });
    }
    if (onChange) onChange({ file, fileList });
  };

  handleClose = () => {
    this.setState({
      visible: false,
    });
  };

  previewFile = file =>
    new Promise(resolve => {
      resolve(getTypeIcon(file));
    });

  render() {
    const { uploader, viewer, value, ...uploadProps } = this.props;
    const { visible, images, index } = this.state;

    const Upload = uploader || DraggerUpload;
    const Viewer = viewer || ImageViewer;
    return (
      <div>
        <Upload
          className="upload-list-inline"
          {...uploadProps}
          listType="picture"
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          previewFile={this.previewFile}
        />
        <Viewer visible={visible} images={images} activeIndex={index} onClose={this.handleClose} />
      </div>
    );
  }
}
